package com.tanovo.config;

import com.alibaba.fastjson.JSONObject;
import com.tanovo.bo.UserCore;
import org.apache.commons.lang.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class UserInfoFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        this.initUserInfo((HttpServletRequest) servletRequest);
        filterChain.doFilter(servletRequest, servletResponse);
    }

    private void initUserInfo(HttpServletRequest request) {
        String userJson = request.getHeader(UserInfoContext.KEY_USERINFO_IN_HTTP_HEADER);
        if (StringUtils.isNotBlank(userJson)) {
            UserCore user = JSONObject.parseObject(userJson, UserCore.class);
            UserInfoContext.setUser(user);
        }
    }


    @Override
    public void destroy() {

    }
}
